package sd.czw.com.miemiegoushop.ui;

import android.app.Activity;
import android.app.ProgressDialog;

import com.google.gson.Gson;
import com.google.gson.stream.JsonReader;
import com.lzy.okgo.callback.AbsCallback;
import com.lzy.okgo.request.base.Request;

import java.lang.reflect.Type;

import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * Created by czw
 * desc 描述：
 * on 2017/9/26.
 */
public class MyCallBak<T> extends AbsCallback<T> {

    private Type type;
    private Class<T> clazz;
    private ProgressDialog dialog;

//    private void initDialog(Activity activity) {
//        dialog = new ProgressDialog(activity);
//        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
//        dialog.setCanceledOnTouchOutside(false);
//        dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
//        dialog.setMessage("请求网络中...");
//    }

    public MyCallBak(Class<T> clazz,Activity activity) {
        this.clazz = clazz;
       // initDialog(activity);
    }


    @Override
    public void onStart(Request<T, ? extends Request> request) {
//        if (dialog != null && !dialog.isShowing()) {
//            dialog.show();
//        }
    }

    @Override
    public void onFinish() {
        //网络请求结束后关闭对话框
//        if (dialog != null && dialog.isShowing()) {
//            dialog.dismiss();
//        }
    }
    @Override
    public void onError(com.lzy.okgo.model.Response<T> response) {
        super.onError(response);
    }

    @Override
    public void onSuccess(com.lzy.okgo.model.Response<T> response) {

    }

    @Override
    public T convertResponse(Response response) throws Throwable {
        ResponseBody body = response.body();
        if (body == null){
            return null;
        }

        T data = null;
        Gson gson = new Gson();
        JsonReader jsonReader = new JsonReader(body.charStream());
        if (type != null){
            data = gson.fromJson(jsonReader,type);
        }

        if (clazz != null){
            data = gson.fromJson(jsonReader,clazz);
        }
        return data;
    }
}
